package com.example.bbs.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.example.bbs.R;
import com.example.bbs.bean.LoginData;
import com.example.bbs.tool.RandomNumber;
import com.example.bbs.tool.SendEmail;
import com.example.bbs.util.HttpUtil;
import com.example.bbs.config.HttpConstant;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class MyRegisterActivity extends AppCompatActivity implements View.OnClickListener {

    static final String LOG_TAG = MyRegisterActivity.class.getSimpleName();
    private long verificationCode=0;            //生成的验证码

    private EditText etRegisterActivityUsername;
    private EditText etRegisterActivityPassword2;
    private EditText etRegisterActivityEmail;
    private EditText etRegisterActivityVerify;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myregister);

        initView();
    }

    private void initView(){
        Button btnRegisterActivityRegister = findViewById(R.id.register_btn_register);
        Button btnRegisterActivityEmail = findViewById(R.id.register_btn_email);
        etRegisterActivityUsername = findViewById(R.id.register_et_account);
        etRegisterActivityPassword2 = findViewById(R.id.register_et_againPsw);
        etRegisterActivityEmail = findViewById(R.id.register_et_email);
        etRegisterActivityVerify = findViewById(R.id.register_et_verify);

        btnRegisterActivityRegister.setOnClickListener(this);
        btnRegisterActivityEmail.setOnClickListener(this);
    }

    public void onClick(View view) {
        if (view.getId() == R.id.register_btn_register) {    //注册按钮
            //获取用户输入的用户名、密码、邮箱
            String username = etRegisterActivityUsername.getText().toString().trim();
            String password = etRegisterActivityPassword2.getText().toString().trim();
            String email = etRegisterActivityEmail.getText().toString().trim();
            int verify_code = Integer.parseInt(etRegisterActivityVerify.getText().toString().trim());
            //注册验证
            if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(email) && judgeVerificationCode(verify_code)) {
                //将用户名和密码加入到数据库中
//                    mDBOpenHelper.add(username, password);
                //新加的
                LoginData loginData = new LoginData(username, password,email);
                HttpUtil.postAsync(HttpConstant.REQUEST_REGISTER, JSON.toJSONString(loginData), (response) -> {
                    if (response != null && response.getBoolean(HttpConstant.FIELD_REPLY))
                        Log.d(LOG_TAG, "add post success");
                    else
                        Log.d(LOG_TAG, "add post failure");
                });

                Intent intent2 = new Intent(this, MainActivity.class);
                startActivity(intent2);
                finish();
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "未完善信息，注册失败", Toast.LENGTH_SHORT).show();
            }
        }
        else if (view.getId() == R.id.register_btn_email){
            String email = etRegisterActivityEmail.getText().toString().trim();
            if (TextUtils.isEmpty(email) || !isEmail(email)){
                Toast.makeText(this, "请输入正确的邮箱", Toast.LENGTH_SHORT).show();
            }
            else {
                sendEmail(email);
                Toast.makeText(this, "验证码已发送，请到邮箱查看后进行验证", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void sendEmail(String email){
        try {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        RandomNumber rn = new RandomNumber();
                        verificationCode = rn.getRandomNumber(6);
                        SendEmail se = new SendEmail(email);
                        se.sendHtmlEmail(verificationCode);//发送html邮件
                        Toast.makeText(MyRegisterActivity.this,"发送成功",Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 正则表达式 判断邮箱格式是否正确
     */

    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    private boolean judgeVerificationCode(int verify) {
        if(verify == verificationCode){    //验证码和输入一致
            Log.d(LOG_TAG,"verify success");
            return true;
        }else{
            Toast.makeText(MyRegisterActivity.this, "verify failed", Toast.LENGTH_LONG).show();
            return false;
        }
    }

}